<template>
    <el-form ref="formRef" :model="form" label-width="100px" style="text-align: center;padding-bottom:10px">
        <el-upload class="avatar-uploader" action="/sys/user/uploadImage" :http-request="uploadImage"
            :show-file-list="false" :before-upload="beforeAvatarUpload" :headers="headers">
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
                <Plus />
            </el-icon>
        </el-upload>
        <el-button @click="handleConfirm">确认更换</el-button>
    </el-form>
</template>

<script setup>
import { ref, defineProps } from 'vue';
import requestUtil, { getServerUrl } from "@/util/request";
import { ElMessage } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import store from "@/store";

const props = defineProps({
    user: {
        type: Object,
        default: () => { },
        required: true
    }
});

const headers = ref({ token: store.getters.GET_TOKEN });

const form = ref({
    id: -1,
    avatar: ''
});
const formRef = ref(null);
const imageUrl = ref("");
form.value = props.user;
imageUrl.value = getServerUrl() + 'image/userAvatar/' + form.value.avatar;

// 上传成功后将显示的图片切换为上传的图片
const uploadImage = async (file) => {
    let param = new FormData();
    param.append('file', file.file);
    console.log('文件', file);

    let request = await requestUtil.fileUpload('/sys/user/uploadImage', param);
    let data = request.data;
    if (data.code == 2000) {
        imageUrl.value = getServerUrl() + data.result.src
        form.value.avatar = data.result.title;
    }
}

// 判断文件的大小和格式
const beforeAvatarUpload = (file) => {
    const isJPG = file.type === 'image/jpeg'
    const isLt2M = file.size / 1024 / 1024 < 2
    if (!isJPG) {
        ElMessage.error('图片必须是jpg格式')
    }
    if (!isLt2M) {
        ElMessage.error('图片大小不能超过2M!')
    }
    return isJPG && isLt2M

}
// 确认更换后发送请求更新数据库
const handleConfirm = async () => {
    let result = await requestUtil.post('/sys/user/updateAvatar', form.value);
    let data = result.data;
    if (data.code == 2000) {
        ElMessage.success('更换成功！');
        store.commit('SET_USERINFO', form.value);
    } else {
        ElMessage.error(data.message);
    }
}

</script>

<style lang="scss" scoped>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409eff;
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}

.avatar {
    width: 120px;
    height: 120px;
    display: block;
}
</style>